import React from 'react';
import { Modal, Form, Input, DatePicker } from 'antd';
import dayjs from 'dayjs';

function TodoForm({ visible, onCancel, onSubmit, initialValues, theme }) {
  const [form] = Form.useForm();

  React.useEffect(() => {
    if (visible && initialValues) {
      form.setFieldsValue({
        ...initialValues,
        deadTime: dayjs(initialValues.deadTime),
      });
    } else {
      form.resetFields();
    }
  }, [visible, initialValues, form]);

  const handleSubmit = async () => {
    try {
      const values = await form.validateFields();
      const submitData = {
        ...values,
        deadTime: values.deadTime.toISOString(),
        createTime: new Date().toISOString(),
        isCompleted: initialValues?.isCompleted || false,
      };
      
      if (initialValues) {
        submitData.id = initialValues.id;
      }
      
      onSubmit(submitData);
    } catch (error) {
      console.error('Validation failed:', error);
    }
  };

  return (
    <Modal
      title={initialValues ? '编辑待办事项' : '添加待办事项'}
      open={visible}
      onCancel={onCancel}
      onOk={handleSubmit}
      destroyOnClose
    >
      <Form
        form={form}
        layout="vertical"
        initialValues={{
          deadTime: dayjs().add(1, 'day'),
        }}
      >
        <Form.Item
          name="name"
          label="事项名称"
          rules={[{ required: true, message: '请输入事项名称' }]}
        >
          <Input placeholder="请输入事项名称" />
        </Form.Item>

        <Form.Item
          name="content"
          label="事项内容"
          rules={[{ required: true, message: '请输入事项内容' }]}
        >
          <Input.TextArea
            placeholder="请输入事项内容"
            rows={4}
          />
        </Form.Item>

        <Form.Item
          name="deadTime"
          label="截止时间"
          rules={[{ required: true, message: '请选择截止时间' }]}
        >
          <DatePicker
            showTime
            format="YYYY-MM-DD HH:mm"
            style={{ width: '100%' }}
          />
        </Form.Item>
      </Form>
    </Modal>
  );
}

export default TodoForm; 